package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyCustomFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CustomFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将请求转换为 HttpServletRequest 以便获取请求 URL
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();

        // 定义静态资源的文件扩展名
        String[] staticResourcesExtensions = { ".css", ".js", ".png", ".jpg", ".jpeg", ".gif", ".woff", ".woff2", ".ttf", ".svg", ".ico" };

        // 判断请求是否为静态资源
        boolean isStaticResource = false;
        for (String extension : staticResourcesExtensions) {
            if (requestURI.endsWith(extension)) {
                isStaticResource = true;
                break;
            }
        }

        if (!isStaticResource) {
            System.out.println("-----------doFilter");
            // 统一全站编码
            servletRequest.setCharacterEncoding("utf-8");
            servletResponse.setContentType("text/html; charset=UTF-8");
            servletResponse.setCharacterEncoding("utf-8");

            // 设置允许跨域的域名，可以根据需要进行修改
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        }

        // 无论是否静态资源，都放行请求
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("CustomFilter destroy");
    }
}
